 #!/usr/bin/python
 # -*- coding: utf-8 -*-

import json
import os, sys
reload(sys)
sys.setdefaultencoding('utf-8')
import traceback
import time,datetime

def format_user_time(time_str):
    try:
        t_str = time_str.split(" ") #April 13, 2011
        t_m = t_str[0].strip(".")
        t_d = t_str[1].strip(",").strip("st|nd|rd|th")
        t_y = t_str[2]
        month_num={"Jan":1,"Feb":2,"Mar":3,"Apr":4,"May":5,"Jun":6,"Jul":7,"Aug":8,"Sept":9,"Oct":10,"Nov":11,"Dec":12,"January":1,"February":2,"March":3,"April":4,"June":6,"July":7,"August":8,"September":9,"October":10,"November":11,"December":12}
        t_m = str(month_num[t_m])
        return (t_d,t_m,t_y)
    except:
        traceback.print_exc()

def get_user_duration(user_profile_fin):

    head="user,formatted_logtime,formatted_jointime,delta_d,groups"
    print>>file("formatted_user_profiles","w"), head
    print>>file("err_format_user","w"),"user,full_name,open_RR,login_time,join_time,groups"
    for u in user_profile_fin.xreadlines():
        try:
            #: EGHM邹Erik Meade邹0邹Last logged in April 13, 2011邹Joined April 13, 2011邹ant#tomcat
            user, user_full_name, open_rr, log_time, join_time, groups \
                    = u.strip().split("邹")
            log_time = log_time[15:] #April 13, 2011
            (log_d,log_m,log_y) = format_user_time(log_time)

            join_time = join_time[7:] #April 13, 2011
            (join_d,join_m,join_y) = format_user_time(join_time)

            formatted_logtime="-".join([log_d,log_m,log_y])
            formatted_jointime="-".join([join_d,join_m,join_y])
            log_time = time.mktime(time.strptime(formatted_logtime, "%d-%m-%Y"))
            join_time = time.mktime(time.strptime(formatted_jointime, "%d-%m-%Y"))
            delta_d = str(int((log_time - join_time)/(60*60*24)))
            print>>file("formatted_user_profiles","a"),\
                    ",".join([user,formatted_logtime,formatted_jointime,delta_d,groups])
        except:
            print>> file("err_format_user",'a'), u.strip()
            traceback.print_exc()

if __name__ == '__main__':
    user_profile_fin = sys.argv[1]
    get_user_duration(file(user_profile_fin,'r'))
